<template>
  <div class="goods-add-container"
       v-loading="loading">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header"
               class="clearfix">
            <span style="font-size:18px;font-weight:900;">基础信息</span>
          </div>
          <div>
            <div>展示图</div>
            <div style="margin-top:10px">
              <el-upload class="avatar-uploader"
                         :on-success="headUploadSuccess"
                         :on-remove="headUploadSuccess"
                         :action="upload_action"
                         :show-file-list="false">
                <img v-if="head"
                     :src="head"
                     class="avatar"> <i v-else
                   class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div class="el-upload__tip"
                   slot="tip">请上传宽高比1/1正方形jpg,png,jpeg照片，且不超过500kb</div>
            </div>

            <div style="margin-top:20px">白底图</div>
            <div style="margin-top:10px">
              <el-upload class="avatar-uploader"
                         :on-success="whiteUploadSuccess"
                         :on-remove="whiteUploadSuccess"
                         :action="upload_action"
                         :show-file-list="false">
                <img v-if="white"
                     :src="white"
                     class="avatar"> <i v-else
                   class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div class="el-upload__tip"
                   slot="tip">请上传宽高比1/1正方形jpg,png,jpeg照片，且不超过500kb</div>
            </div>
            <div style="margin-top:20px">商品图片和视频（{{img.length}}/9）</div>
            <div style="margin-top:10px;">

              <ul class="image-upload">
                <draggable v-model="img"
                           @update="dataDragEnd">
                  <transition-group class="uploader">
                    <div v-for="(item, index) in img"
                         :key="item.url"
                         style="padding-right:10px">
                      <img v-if="item.url"
                           style="width:146px;height: 146px"
                           :src="item.url">
                      <div class="icon-container">
                        <span v-if="item.url"
                              @click="handlePreviewNew(index)">
                          <i class="el-icon-zoom-in"></i>
                        </span>
                        <span v-if="item.url"
                              @click="handleRemoveNew(item, index)">
                          <i class="el-icon-delete"></i>
                        </span>
                      </div>
                    </div>
                  </transition-group>
                </draggable>

                <el-upload :action="upload_action"
                           :data="{store:'product'}"
                           :on-success="imgUploadSuccess"
                           list-type="picture-card"
                           :show-file-list="false">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </ul>
              <!-- <el-upload :action="upload_action"
                         :data="{store:'product'}"
                         :on-success="imgUploadSuccess"
                         :on-remove="imgRemoveSuccess"
                         list-type="picture-card"
                         :file-list="img">
                <i class="el-icon-plus"></i>
              </el-upload> -->
            </div>
            <div class="el-upload__tip">最多上传9个素材，其中最多上传1个视频（mp4格式），视频时长不超过60秒，视频大小不超过200M。视频将默认展示在图片之前，拖拽图片可进行排序，单张图片需限制在10M以内。</div>

            <el-row :gutter="30"
                    style="margin-top:20px">
              <el-col :span="12">
                <div>商品标题</div>
                <div style="margin-top:10px">
                  <el-input v-model="title"
                            placeholder="请输入内容"
                            maxlength="40"
                            show-word-limit></el-input>
                </div>
              </el-col>
              <el-col :span="12">
                <div>商品编码</div>
                <div style="margin-top:10px">
                  <el-input v-model="code"
                            placeholder="请输入内容"></el-input>
                </div>
              </el-col>
              <el-col :span="12"
                      style="margin-top:20px">
                <div>所属分组</div>
                <div style="margin-top:10px">
                  <el-select v-model="category_id"
                             placeholder="请选择"
                             multiple
                             style="width:100%">
                    <el-option v-for="item in category_list"
                               :key="item.id"
                               :label="item.title"
                               :value="item.id+''">
                    </el-option>
                  </el-select>
                </div>
              </el-col>
              <el-col :span="12"
                      style="margin-top:20px">
                <div>商品描述(选填)</div>
                <div style="margin-top:10px">
                  <el-input v-model="describe"
                            placeholder="请输入内容"
                            maxlength="20"
                            show-word-limit></el-input>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <el-card class="box-card"
                 style="margin-top:20px">
          <div slot="header"
               class="clearfix">
            <span style="font-size:18px;font-weight:900;">商品详情</span>
          </div>
          <div>
            <el-input type="textarea"
                      :rows="8"
                      placeholder="请输入内容"
                      v-model="detail_text"
                      maxlength="2000"
                      show-word-limit>
            </el-input>
            <div style="margin-top:20px">
              <ul class="image-upload">
                <draggable v-model="detail_img"
                           @update="dataDragEndEetailImg">
                  <transition-group class="uploader">
                    <div v-for="(item, index) in detail_img"
                         :key="item.url"
                         style="padding-right:10px">
                      <img v-if="item.url"
                           style="width:146px;height: 146px"
                           :src="item.url">
                      <div class="icon-container">
                        <span v-if="item.url"
                              @click="handlePreviewNew(index)">
                          <i class="el-icon-zoom-in"></i>
                        </span>
                        <span v-if="item.url"
                              @click="handleRemoveDetail(item, index)">
                          <i class="el-icon-delete"></i>
                        </span>
                      </div>
                    </div>
                  </transition-group>
                </draggable>

                <el-upload :action="upload_action"
                           :data="{store:'product'}"
                           :on-success="detailUploadSuccess"
                           :file-list="detail_img"
                           list-type="picture-card"
                           :show-file-list="false">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </ul>
            </div>
            <div style="margin-top:10px;color:#999;font-size:14px">最多上传20个素材，拖拽可进行排序，单张图片需限制在10M以内</div>
          </div>
        </el-card>

        <el-card class="box-card"
                 style="margin-top:20px">
          <div slot="header"
               class="clearfix">
            <span style="font-size:18px;font-weight:900;">商品参数</span>
          </div>
          <div style="margin-top:20px">
            <el-form ref="form"
                     label-width="80px">
              <el-form-item label="年份">
                <el-input v-model="year"
                          type="year"
                          placeholder="请输入内容"></el-input>
              </el-form-item>
              <el-form-item label="产地">
                <el-input v-model="area"
                          placeholder="请输入内容"></el-input>

              </el-form-item>
              <el-form-item label="种类">
                <el-input v-model="kind"
                          placeholder="请输入内容"></el-input>

              </el-form-item>
              <el-form-item label="级别">
                <el-input v-model="level"
                          placeholder="请输入内容"></el-input>

              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header"
               class="clearfix">
            <span style="font-size:18px;font-weight:900;">规格参数</span>
          </div>
          <div>
            <div class="goods-attr-item"
                 v-for="(item,index) in goods_item">
              <div class="goods-item-row">
                <div class="goods-item-row-left">
                  <div class="goods-item-title">
                    规格{{index+1}}
                  </div>
                  <div class="goods-item-input">
                    <el-input v-model="item.title"
                              placeholder="请输入内容"></el-input>
                  </div>
                  <div class="goods-item-check">
                    <el-upload :action="upload_action"
                               :data="{store:'product'}"
                               :on-success="(res)=> {
                                  return itemUploadSuccess(res, index);
                                }"
                               :limit="1"
                               :show-file-list="false">
                      <img v-if="item.head"
                           :src="item.head"
                           class="item-head">
                      <el-button v-else
                                 icon="el-icon-picture-outline"
                                 circle></el-button>
                    </el-upload>
                    <div style="margin-left:20px">
                      <el-checkbox v-model="item.status">上架</el-checkbox>
                    </div>
                  </div>
                </div>
                <div class="goods-item-row-right"
                     @click="delGoods(index)">
                  删除属性
                </div>
              </div>
              <div class="goods-content-row">
                <div class="content-row-left">
                  <el-input v-model="item.price"
                            placeholder="请输入价格"
                            style="width:300px"></el-input>
                </div>
                <div class="content-row-right">
                  元
                </div>
              </div>
              <div class="goods-content-row">
                <div class="content-row-left">
                  <el-input v-model="item.stock"
                            placeholder="请输入库存"
                            style="width:300px"></el-input>
                </div>
                <div class="content-row-right">
                  库存
                </div>
              </div>
              <div class="goods-content-row">
                <div class="content-row-left">
                  <el-input v-model="item.min_order"
                            placeholder="请输入最少购买量"
                            style="width:300px"></el-input>
                </div>
                <div class="content-row-right">
                  件起订
                </div>
              </div>
            </div>
            <div>
              <el-button @click="addGoods">新增参数</el-button>
            </div>

          </div>
        </el-card>

        <el-button type="danger"
                   style="margin-top:20px"
                   @click="submitPost()">{{id?"保存修改":"新增商品"}}</el-button>
      </el-col>
    </el-row>
  </div>
</template>
    
<script>
import { addData, getRead, editData } from "@/api/product";
import { getList as getCategoryList } from "@/api/productCategory";
import draggable from "vuedraggable";
export default {
  data () {
    return {
      loading: false,
      id: null,
      head: '',
      white: '',
      img: [],
      title: '',
      describe: '',
      code: '',
      category_id: [],
      upload_action: process.env.VUE_APP_UPLOAD_ACTION,
      detail_text: '',
      detail_img: [],
      category_list: [],
      kind: '',
      year: null,
      material: null,
      level: null,
      area: null,
      goods_item: [
        {
          title: '',
          head: '',
          price: 0,
          stock: 999999,
          min_order: 0
        }
      ],
    }
  },
  components: {
    draggable,
  },
  created () {
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.fetchData(this.id)
    }
    this.fetchCategoryData()
  },
  methods: {
    fetchData (id) {
      getRead({ id: id }).then(response => {
        let data = response.data
        this.category_id = data.category_id
        this.code = data.code
        this.title = data.title
        this.year = data.year
        this.area = data.area
        this.kind = data.kind
        this.level = data.level
        this.white = data.white
        this.describe = data.describe
        this.detail_text = data.detail_text
        this.goods_item = data.goods_item
        data.img.forEach(element => {
          this.img.push({
            "url": element
          })
        });


        data.detail_img.forEach(element => {
          this.detail_img.push({
            "url": element
          })
        });
        this.head = data.head
      })
    },


    fetchCategoryData () {
      getCategoryList().then(response => {
        this.category_list = response.data.data
      })
    },

    //提交数据
    submitPost () {
      //this.loading = true
      if (this.title == '') {
        this.$message.error('请输入商品的标题');
        this.loading = false
        return false;
      }
      if (this.img.length == 0) {
        this.$message.error('请上传至少一个商品图片和视频');
        this.loading = false
        return false;
      }
      let data = {
        head: this.head,
        white: this.white,
        year: this.year,
        area: this.area,
        kind: this.kind,
        level: this.level,
        code: this.code,
        category_id: this.category_id,
        img: this.img,
        title: this.title,
        describe: this.describe,
        detail_text: this.detail_text,
        detail_img: this.detail_img,
        goods_item: this.goods_item,
        material: this.material,
        popular: this.popular,
        mode: this.mode,
      }
      if (this.id) {
        data.id = this.id
        editData(data).then(response => {
          this.loading = false
          if (response.code == 1000) {
            this.$message({
              message: '数据保存成功',
              type: 'success'
            });

          } else {
            this.$message.error(response.msg);
          }
        })
      } else {
        addData(data).then(response => {
          this.loading = false
          if (response.code == 1000) {
            this.$message({
              message: '数据保存成功',
              type: 'success'
            });
          } else {
            this.$message.error(response.msg);
          }
        })
      }
    },
    //输入框改变
    changeGoodsItem () {
      setTimeout(() => {
        this.doExchange(1)
      }, 500);
    },

    //删除图片
    handleRemoveNew (file, index) {
      this.img.splice(index, 1)
    },

    // 处理图片预览效果
    handlePreviewNew (index) {
      this.previewPath = this.fileList[index].url
      this.previewVisible = true
    },

    //拖拽图片排序
    dataDragEnd () {
      // 拖拽图片更换位置 并重新从1开始排序
      this.img.forEach((item, index) => {
        item.sortNum = index + 1
      })
      //过滤一下url为空的数据
      this.img = this.img.filter(item => {
        return item.url != ''
      });
    },
    dataDragEndEetailImg () {
      // 拖拽图片更换位置 并重新从1开始排序
      this.detail_img.forEach((item, index) => {
        item.sortNum = index + 1
      })
      //过滤一下url为空的数据
      this.detail_img = this.detail_img.filter(item => {
        return item.url != ''
      });
    },
    //删除图片
    handleRemoveDetail (file, index) {
      this.detail_img.splice(index, 1)
    },

    itemUploadSuccess (response, index) {
      this.goods_item[index].head = response.data.data;
    },
    whiteUploadSuccess (response, file, fileList) {
      this.white = response.data.data;
    },
    whiteRemoveSuccess (file, fileList) {
      this.white = '';
    },
    /**
     * 上传头图
     */
    headUploadSuccess (response, file, fileList) {
      this.head = response.data.data;
    },
    headRemoveSuccess (file, fileList) {
      this.head = '';
    },

    /**
     * 上传详情图片
     */
    detailUploadSuccess (response, file, fileList) {
      this.detail_img.push({ "url": response.data.data })
    },
    /**
     * 上传图片
     */
    imgUploadSuccess (response, file, fileList) {
      this.img.push({ "url": response.data.data })
    },
    delGoods (index) {
      if (this.goods_item.length == 1) {
        this.$message.error("必须保留一个规格");
      } else {
        this.goods_item.splice(index, 1)
      }
    },
    addGoods () {
      this.goods_item.push(
        {
          title: '',
          head: '',
          pirce: 0,
          stock: 999999,
          min_order: 0,
          status: 0,
        })
    },
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>


<style lang="scss" scoped>
.image-upload {
  display: flex;
  list-style-type: none;
  flex-flow: row wrap;
  margin: 0;
  padding: 0;

  .uploader {
    display: flex;
    align-items: center;

    .upload-list {
      margin-right: 8px;
      width: 146px;
      height: 146px;
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #c0ccda;
      position: relative;

      &:hover {
        .icon-container {
          display: block;
          transition: all 0.5s;
        }
      }

      .icon-container {
        position: absolute;
        display: none;
        transition: all 0.5s;
        width: 146px;
        height: 146px;
        line-height: 146px;
        color: #fff;
        font-size: 20px;
        text-align: center;
        border-radius: 8px;
        top: 0;
        left: 0;
        background-color: rgba(0, 0, 0, 0.5);

        span {
          margin: 0 10px;
          cursor: pointer;
        }
      }
    }
  }
}
.goods-add-container {
  font-family: PingFang SC;
  padding: 30px;
  margin: 0 auto;

  .goods-attr-item {
    padding: 20px;
    background-color: #f5f5f5;
    border-radius: 10px;
    margin-bottom: 20px;
    .goods-item-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .goods-item-row-left {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        height: 40px;
        .goods-item-title {
          margin-right: 20px;
          font-weight: 400;
        }
        .goods-item-check {
          display: flex;
          align-items: center;
          margin-left: 20px;
          .item-head {
            width: 50px;
            height: 50px;
            border-radius: 5px;
          }
        }
      }
      .goods-item-row-right {
        color: #0b4c8d;
        cursor: pointer;
      }
    }
    .goods-content-row {
      margin-top: 10px;
      padding-left: 60px;
      display: flex;
      align-items: center;
      .content-row-right {
        padding-left: 10px;
        font-size: 16px;
      }
    }
    .addTxt {
      color: #0b4c8d;
      display: flex;
      align-items: center;
      padding: 20px;
      padding-left: 60px;
      cursor: pointer;
    }
  }
}
</style>